package com.elong.businesstravel.modules.home;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.debug.WriteLogCat;
import com.android.support.jhf.dialog.CustomWaitDialog;
import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.BaseErrorListener;
import com.android.support.jhf.network.BaseStateListener;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.AsyncHttpRequest;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.network.loopj.android.http.TextHttpResponseHandler;
import com.android.support.jhf.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.android.support.jhf.utils.AndroidUniqueSerialNumber;
import com.android.support.jhf.utils.CoordinateConversion;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.FileUtils;
import com.android.support.jhf.utils.NetworkStatusUtils;
import com.android.support.jhf.onClick.OnClickListener;
import com.android.support.jhf.onClick.OnClickNetworkStatusListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClientOption.LocationMode;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.Constant;
import com.elong.businesstravel.base.baidusdk.location.BaiduLocation;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.baseactivity.BaseFragmentActivity;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.umeng.feedback.ConversationActivity;
import com.elong.businesstravel.base.utils.AndroidManifestUtil;
import com.elong.businesstravel.base.utils.AppUserId;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.entitys.City;
import com.elong.businesstravel.entitys.Poi;
import com.elong.businesstravel.include.Version;
import com.elong.businesstravel.modules.collect.HotelCollectActivity;
import com.elong.businesstravel.modules.help.HelpActivity;
import com.elong.businesstravel.modules.home.adapter.HomePagerAdapter;
import com.elong.businesstravel.modules.home.hotel.HotelFragment;
import com.elong.businesstravel.modules.home.hotel.dialog.HotelPriceLevelDialog;
import com.elong.businesstravel.modules.home.hotel.hotelshow.HotelSearchResultActivity;
import com.elong.businesstravel.modules.home.hotel.search.HotelCitySelectActivity;
import com.elong.businesstravel.modules.home.hotel.search.HotelDestineDateActivity;
import com.elong.businesstravel.modules.home.hotel.search.HotelLocationSelectActivity;
import com.elong.businesstravel.modules.home.ticket.TrainTicketFragment;
import com.elong.businesstravel.modules.login.LoginActivity;
import com.elong.businesstravel.modules.member.MemberCenterActivity;
import com.elong.businesstravel.modules.orders.OrdersActivity;
import com.elong.businesstravel.modules.orders.SendRecordCommentActivity;
import com.elong.businesstravel.protocol.baseresponse.BaseELongJsonHttpResponse;
import com.elong.businesstravel.protocol.baseresponse.IHttpResponse;
import com.elong.businesstravel.protocol.city.GetAllCityPoiRequest;
import com.elong.businesstravel.protocol.city.GetAllCityPoiResponse;
import com.elong.businesstravel.protocol.city.GetCityByLatLngRequest;
import com.elong.businesstravel.protocol.city.GetCityByLatLngResponse;
import com.elong.businesstravel.protocol.city.GetCityRequest;
import com.elong.businesstravel.protocol.city.GetCityResponse;
import com.elong.businesstravel.protocol.hotel.GuesshotelRequest;
import com.elong.businesstravel.protocol.hotel.GuesshotelResponse;
import com.elong.businesstravel.protocol.login.GetequipmentRequest;
import com.elong.businesstravel.protocol.login.GetequipmentResponse;
import com.elong.businesstravel.protocol.ticket.GetStationListRequest;
import com.elong.businesstravel.protocol.ticket.GetStationListResponse;
import com.elong.businesstravel.protocol.version.GetVersionRequest;
import com.elong.businesstravel.wxapi.WXEntryActivity;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.umeng.update.UmengUpdateAgent;

import android.R.string;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 新版差旅通首页
 * 
 * @author lenovo
 * 
 */
public class NewHomeActivity extends BaseFragmentActivity {

	private ViewPager mViewPager;
	private HomePagerAdapter mSectionsPagerAdapter;

	private TextView mDot1TextView;
	private TextView mDot2TextView;

	/** 附近 */
	private BaiduLocation mNearyBaiduLocation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_home);

		// 开启umeng推送
		PushAgent mPushAgent = PushAgent.getInstance(mContext);
		mPushAgent.enable();

		mApplication.mFlagHome = true;

		SaveUserOperate.setLastVersionCode(mContext, Version.versionCode + "");

		init();

	}

	protected void init() {

		mApplication.factoryDate();

		umengSDKImploded();

		mDot1TextView = (TextView) findViewById(R.id.dot1TextView);
		mDot2TextView = (TextView) findViewById(R.id.dot2TextView);
		mDot1TextView.setBackgroundColor(Color.RED);
		mDot2TextView.setBackgroundColor(Color.GREEN);

		mViewPager = (ViewPager) findViewById(R.id.viewPager);
		mSectionsPagerAdapter = new HomePagerAdapter(
				getSupportFragmentManager());
		mViewPager.setAdapter(mSectionsPagerAdapter);
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				if (0 == arg0) {
					mDot1TextView.setBackgroundColor(Color.RED);
					mDot2TextView.setBackgroundColor(Color.GREEN);
				} else if (1 == arg0) {
					mDot1TextView.setBackgroundColor(Color.GREEN);
					mDot2TextView.setBackgroundColor(Color.RED);
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		setListener();

		if (null == mApplication.mCity) {
			getCityListRefreshView();
		}

		if(null == mApplication.mTrainStations){
			getTrainListRefreshView();
		}
		
		// 用于下载所有城市的poi，开发时候用
		// getAllCityPoi();

		getequipment();

		if (!NetworkStatusUtils.networkStatusOK(mContext)) {
			showNetworkDialog();
		}
		
		DebugLog.logI("NewHomeActivity");

	}

	/**
	 * 如果没有连接网络显示对话框
	 */
	private void showNetworkDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setMessage("您的应用没有联网，请打开网络设置连接网络，或者设置应用的联网权限。");
		customAlertDialog.setLeftButton("知道了", new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});
		customAlertDialog.setRightButtonGone();
		customAlertDialog.show();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
		if (null != intent) {
			String activityString = intent.getStringExtra("Activity");
			DebugLog.logI("HomeActivity onNewIntent : " + activityString);
		}
		DebugLog.logI("HomeActivity onNewIntent");
	}

	/**
	 * 友盟sdk集成
	 */
	private void umengSDKImploded() {
		// 自动更新
		UmengUpdateAgent.setUpdateAutoPopup(true);
		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(mApplication);

	}

	private void goMemberCenter() {
		if (!"".equals(AppUserId.getUserId(mContext))) {
			Intent intent = new Intent(mContext, MemberCenterActivity.class);
			startActivity(intent);
		} else {
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 4);
		}
	}

	/**
	 * 跳转到订单页
	 */
	private void goMemberOrders() {
		if (!"".equals(AppUserId.getUserId(mContext))) {
			Intent intent = new Intent(mContext, OrdersActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		} else {
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 5);
		}
	}

	/**
	 * 获取城市列表刷新界面
	 */
	private void getCityListRefreshView() {
		getCityList(new IHttpResponse() {

			@Override
			public void onResponse(
					ResponseHandlerInterface responseHandlerInterface) {
				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {
					}
				});
			}
		});
	}
	
	/**
	 * 获取车站列表刷新界面
	 */
	private void getTrainListRefreshView() {
		getTrainList(new IHttpResponse() {

			@Override
			public void onResponse(
					ResponseHandlerInterface responseHandlerInterface) {
				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {
					}
				});
			}
		});
	}

	/**
	 * 获取城市列表
	 * 
	 * @param iHttpResponse
	 */
	private void getCityList(final IHttpResponse iHttpResponse) {

		final Md5FileNameGenerator md5FileNameGenerator = new Md5FileNameGenerator();
		final GetCityRequest getCityRequest = new GetCityRequest(mContext);
		final String cacheKeyString = getCacheDir() + "/"
				+ md5FileNameGenerator.generate(getCityRequest.getCacheKey());

		NetworkClient.getNetworkClient().PostRequest(getCityRequest,
				new GetCityResponse() {
					@Override
					public void onResponse(
							final ResponseHandlerInterface responseHandlerInterface) {
						mApplication.mCity = ((GetCityResponse) responseHandlerInterface).mCity;
						String responseString = ((GetCityResponse) responseHandlerInterface).responseString;
						FileUtils.saveFile(responseString, new File(
								cacheKeyString));
						if (null != iHttpResponse) {
							iHttpResponse.onResponse(responseHandlerInterface);
						}
					}
				});
	}
	
	/**
	 * 获取车站列表
	 * 
	 * @param iHttpResponse
	 */
	private void getTrainList(final IHttpResponse iHttpResponse) {

		final Md5FileNameGenerator md5FileNameGenerator = new Md5FileNameGenerator();
		final GetStationListRequest getStationListRequest = new GetStationListRequest(mContext);
		final String cacheKeyString = getCacheDir() + "/"
				+ md5FileNameGenerator.generate(getStationListRequest.getCacheKey());

		NetworkClient.getNetworkClient().PostRequest(getStationListRequest,
				new GetStationListResponse() {
					@Override
					public void onResponse(
							final ResponseHandlerInterface responseHandlerInterface) {
						mApplication.mTrainStations = ((GetStationListResponse) responseHandlerInterface).trainStations;
						String responseString = ((GetStationListResponse) responseHandlerInterface).responseString;
						FileUtils.saveFile(responseString, new File(
								cacheKeyString));
						if (null != iHttpResponse) {
							iHttpResponse.onResponse(responseHandlerInterface);
						}
					}
				});
	}

	/**
	 * 跳转到附近酒店
	 */
	private void goNearbyHotel() {
		showWaitDialog("正在定位...", new OnKeyCancel() {

			@Override
			public void onKeyCancelListener() {
				mNearyBaiduLocation.stopLocation();
			}
		});

		mNearyBaiduLocation = new BaiduLocation(mContext);
		mNearyBaiduLocation.setLocationParams(LocationMode.Hight_Accuracy,
				false, 1000, true, "bd09ll", true);
		mNearyBaiduLocation.setLocationListener(new BDLocationListener() {

			@Override
			public void onReceivePoi(BDLocation arg0) {

			}

			@Override
			public void onReceiveLocation(BDLocation arg0) {

				mNearyBaiduLocation.stopLocation();

				if (null == arg0 || 0 == arg0.getLatitude()
						|| 0 == arg0.getLongitude()
						|| TextUtils.isEmpty(arg0.getCity())) {
					HandlerToastUI.getHandlerToastUI(mContext, "定位失败");
					hideWaitDialog();
					return;
				}

				mApplication.mBdLocation = arg0;

				double[] lngLat = CoordinateConversion.bd2gg(
						arg0.getLatitude(), arg0.getLongitude());

				getCityByLatLng(new IHttpResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {

						double[] lngLat = CoordinateConversion.bd2gg(
								mApplication.mBdLocation.getLatitude(),
								mApplication.mBdLocation.getLongitude());

						Intent intent = new Intent(mContext,
								HotelSearchResultActivity.class);
						intent.putExtra("sort", mApplication.mHotelLocSorts);
						intent.putExtra("sorts", "4");
						intent.putExtra("PoiName", "当前位置");
						intent.putExtra("googlelat", lngLat[1]);
						intent.putExtra("googlelng", lngLat[0]);
						intent.putExtra("LocationCity",
								mApplication.mLocationCity);
						startActivity(intent);
					}
				}, lngLat[1], lngLat[0]);

			}
		});
		mNearyBaiduLocation.startLocation();

	}
	
	/**
	 * 定位之后联网获取城市实体
	 * 
	 * @param latString
	 * @param lngString
	 */
	public void getCityByLatLng(final IHttpResponse iHttpResponse,
			final double latString, final double lngString) {
		NetworkClient.getNetworkClient().PostRequest(
				new GetCityByLatLngRequest(mContext, latString, lngString),
				new GetCityByLatLngResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {

						mApplication.mLocationCity = ((GetCityByLatLngResponse) responseHandlerInterface).mCity;

						if (null != iHttpResponse) {
							iHttpResponse.onResponse(responseHandlerInterface);
						}

						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {

								hideWaitDialog();

							}
						});
					}
				}, new BaseStateListener() {
					@Override
					public void onFinish(AsyncHttpRequest asyncHttpRequest) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								hideWaitDialog();

							}
						});

					}
				}, new BaseErrorListener() {
				});
	}

	private void goHotelCollectActivity() {
		if (!"".equals(AppUserId.getUserId(mContext))) {
			Intent intent = new Intent(mContext, HotelCollectActivity.class);
			startActivity(intent);
		} else {
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 6);
		}
	}

	protected void setListener() {

		ViewGroup memberLayout = (ViewGroup) findViewById(R.id.memberLayout);
		memberLayout.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goMemberCenter();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		ViewGroup nearbyLayout = (ViewGroup) findViewById(R.id.nearbyLayout);
		nearbyLayout.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goNearbyHotel();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		ViewGroup ordersLayout = (ViewGroup) findViewById(R.id.ordersLayout);
		ordersLayout.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goMemberOrders();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		ViewGroup collectLayout = (ViewGroup) findViewById(R.id.collectLayout);
		collectLayout.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				goHotelCollectActivity();
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});

		ViewGroup newDoingLayout = (ViewGroup) findViewById(R.id.newDoingLayout);
		newDoingLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

			}
		});

		ViewGroup feedbackLayout = (ViewGroup) findViewById(R.id.feedbackLayout);
		feedbackLayout.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				goConversationActivity();
			}
		});

	}

	/**
	 * 跳转到反馈界面
	 */
	private void goConversationActivity() {
		if (TextUtils.isEmpty(AppUserId.getUserId(mContext))) {
			// 登陆
			Intent intent = new Intent(mContext, LoginActivity.class);
			startActivityForResult(intent, 7);
		} else {
			// 反馈
			Intent intent = new Intent(mContext, ConversationActivity.class);
			startActivity(intent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 0: {
			// 选择城市返回
			switch (resultCode) {
			case RESULT_OK: {
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 1: {
			// 选择价格/星级
			switch (resultCode) {
			case RESULT_OK: {
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 2: {
			// 选择位置返回
			switch (resultCode) {
			case RESULT_OK: {
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 3: {
			// 入住酒店时间和天数
			switch (resultCode) {
			case RESULT_OK: {
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 4: {
			// 登陆返回,跳转到会员中心
			switch (resultCode) {
			case RESULT_OK: {
				goMemberCenter();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 5: {
			// 登陆返回,跳转到查看订单
			switch (resultCode) {
			case RESULT_OK: {
				goMemberOrders();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 6: {
			// 登陆返回，跳转到收藏
			switch (resultCode) {
			case RESULT_OK: {
				goHotelCollectActivity();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		case 7: {
			// 登陆返回，跳转到反馈界面
			switch (resultCode) {
			case RESULT_OK: {
				goConversationActivity();
				break;
			}
			case RESULT_CANCELED: {
				break;
			}
			default:
				break;
			}
			break;
		}
		default:
			break;
		}
	}

	private void quit() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog.setMessage("是否退出应用");
		customAlertDialog.setLeftButton("是", new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// WriteLogCat.factory().stopLogCarInfo();
				finish();
				System.exit(0);
			}
		});
		customAlertDialog.setRightButton("否", new View.OnClickListener() {

			@Override
			public void onClick(View v) {

			}
		});
		customAlertDialog.show();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// private void getVersion() {
	// NetworkClient.getNetworkClient().PostRequest(
	// new GetVersionRequest(mContext), new BaseJsonHttpResponse() {
	//
	// @Override
	// public void onSuccess(int statusCode, Header[] headers,
	// String responseString) {
	// // try {
	// // JSONObject jsonObject = new
	// // JSONObject(responseString);
	// // HandlerToastUI.getHandlerToastUI(mContext,
	// // jsonObject.getString("resultdes"));
	// // } catch (JSONException e) {
	// // e.printStackTrace();
	// // }
	//
	// }
	//
	// });
	//
	// }

	/**
	 * 用于下载所有城市的poi，开发时候用
	 */
	private void getAllCityPoi() {
		NetworkClient.getNetworkClient().PostRequest(
				new GetAllCityPoiRequest(mContext),
				new GetAllCityPoiResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
					}

				});

	}

	@Override
	protected void refreshDateUI(String showDateUIString) {
		super.refreshDateUI(showDateUIString);
//		if(null != mHotelFragment){
//			mHotelFragment.refreshDateUI(showDateUIString);
//		}
	}

	/**
	 * 发送用于推送的token
	 */
	private void getequipment() {
		String device_token = UmengRegistrar.getRegistrationId(mContext);
		NetworkClient.getNetworkClient().PostRequest(
				new GetequipmentRequest(mContext, device_token),
				new GetequipmentResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						super.onResponse(responseHandlerInterface);

					}
				}, new BaseStateListener() {
				}, new BaseErrorListener() {
				});
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

}
